﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using TiaoTiaoCode.AutoUpdate.Common.Strings;

namespace TiaoTiaoCode.AutoUpdate.WebApi.Controllers
{
    /// <summary>
    /// 认证服务
    /// </summary>    
    public class AuthController : ApiController
    {
        readonly IConfiguration _config;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="configuration"></param>
        public AuthController(IConfiguration configuration)
        {
            _config = configuration;
        }

        /// <summary>
        /// Token
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost("token")]
        public IActionResult Token()
        {
            var jwtConfig = _config.GetSection("Jwt");
            //秘钥，就是标头，这里用Hmacsha256算法，需要256bit的密钥
            var securityKey = new SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtConfig.GetValue<string>("SecurityKey"))), SecurityAlgorithms.HmacSha256);
            //Claim，JwtRegisteredClaimNames中预定义了好多种默认的参数名，也可以像下面的Guid一样自己定义键名.
            //ClaimTypes也预定义了好多类型如role、email、name。Role用于赋予权限，不同的角色可以访问不同的接口
            //相当于有效载荷
            var apiKey = Guid.NewGuid().ToString("N");
            var claims = new Claim[] {
                new Claim(JwtRegisteredClaimNames.Iss,jwtConfig.GetValue<string>("Issuer")),
                new Claim(JwtRegisteredClaimNames.Aud,jwtConfig.GetValue<string>("Audience")),
                new Claim(ClaimTypeString.ApiKey,apiKey),
                new Claim(ClaimTypeString.UserId,apiKey),
                new Claim(ClaimTypeString.UserName,apiKey)
            };

            SecurityToken securityToken = new JwtSecurityToken(
                signingCredentials: securityKey,
                expires: DateTime.Now.AddMinutes(2),//过期时间
                claims: claims
            );

            var token = new JwtSecurityTokenHandler().WriteToken(securityToken);

            //生成jwt令牌
            return Success(new { Token = token.ToString(), ApiKey = apiKey });
        }
    }
}
